import localCache from "@/utils/localCache";
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import { firstPath } from "@/utils/mapMenu";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/main"
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/view/login/index.vue")
  },
  {
    path: "/main",
    name: "main",
    component: () => import("@/view/main/index.vue")
  },
  {
    path: "/:pathMath(.*)*",
    name: "404",
    component: () => import("@/view/not-found/404.vue")
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});
router.beforeEach((to) => {
  const token = localCache.getCache("token");
  if (to.path !== "/login") {
    if (!token) {
      return "/login";
    } else if (token && (to.path === "/main" || to.path === "/main/")) {
      return firstPath;
    } else if (token && to.path === "/login/") {
      return "/main";
    }
  } else if (to.path === "/login") {
    if (token) {
      return "/main";
    }
  }
});

export default router;
